# coding=UTF-8

from world_model import World
import video_tool
import shutil
import os
import pickle
import cv2

name = '25.10'

# 保存世界
def save_world(world):
	# 清除不能被保存的信息
	world.cap_use = 0 # 释放摄像头
	world.cap_show = 0
	# 保存数据
	if not os.path.exists('./data'):
		os.mkdir('./data/')
	file = open('./data/world-' + name + '-' + str(world.time) + '.data', "wb")
	pickle.dump(world, file)
	file.close()

# 加载世界
def load_world():
	# 加载数据
	files = os.listdir('./data-use')
	file_name = './data-use/' + files[0]
	file = open(file_name, "rb")
	world = pickle.load(file)
	file.close()
	# 重新初始化摄像头
	if world.arrival_enable:
		world.cap_use = cv2.VideoCapture(World.cap_use_num)
		world.cap_show = cv2.VideoCapture(World.cap_show_num)
	return world

# 清文件夹
if os.path.exists('./result-' + name):
	shutil.rmtree('./result-' + name)
os.mkdir('./result-' + name + '/')
os.mkdir('./result-' + name + '/pic-1/')
os.mkdir('./result-' + name + '/pic-2/')
os.mkdir('./result-' + name + '/pic-3/')
os.mkdir('./result-' + name + '/pic-4/')
os.mkdir('./result-' + name + '/pic-5/')
os.mkdir('./result-' + name + '/pic-6/')
os.mkdir('./result-' + name + '/pic-7/')
os.mkdir('./result-' + name + '/pic-8/')
os.mkdir('./result-' + name + '/pic-9/')
os.mkdir('./result-' + name + '/log-1/')
os.mkdir('./result-' + name + '/pic-aim/')

# 初始化世界
world = World()
world.init_core(20) # 20
world.init_time()
# world = load_world() # 加载世界 world-19.6-200000.data
run_time = 200000 # 200000
for i in range(run_time):
	print(i, world.time)
	world.tick_tock()
	# if i > run_time - 200 or i % 1000 == 0:
	if i > run_time - 100 or (i > run_time - 1000 and i % 10 == 0) or i % 2000 == 0:
		world.draw_world(name)
print('ok')
save_world(world) # 保存世界

if world.arrival_enable:
	video_tool.turn_arrival('./result-' + name + '/pic-1/', './result-' + name + '/pic-2/', \
		            './result-' + name + '/pic-3/', './result-' + name + '/pic-4/', \
		            './result-' + name + '/pic-aim/')
else:
	video_tool.turn_base('./result-' + name + '/pic-1/', './result-' + name + '/pic-2/', \
		            './result-' + name + '/pic-5/', './result-' + name + '/pic-6/', \
		            './result-' + name + '/pic-7/', './result-' + name + '/pic-8/', \
		            './result-' + name + '/pic-9/', \
		            './result-' + name + '/pic-aim/')
video_tool.png2mp4('./result-' + name + '/pic-aim/', './result-' + name)

